import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';

class AnimatedListPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return AnimatedListPageState();
  }
}

class AnimatedListPageState extends State<AnimatedListPage> {
  final GlobalKey<AnimatedListState> _listKey = GlobalKey();
  List<String> _data = ['Horse', 'Cow', 'Camel', 'Sheep', 'Goat'];

void _removeSingleItems() {
    int removeIndex = 2;
    String removedItem = _data.removeAt(removeIndex);
    // This builder is just so that the animation has something
    // to work with before it disappears from view since the original
    // has already been deleted.
    AnimatedListRemovedItemBuilder builder = (context, animation) {
      // A method to build the Card widget.
      return _buildItem(removedItem, animation);
    };
    _listKey.currentState.removeItem(removeIndex, builder);
  }

  void _insertSingleItem() {
    String item = "Pig";
    int insertIndex = 2;
    _data.insert(insertIndex, item);
    _listKey.currentState.insertItem(insertIndex);
  }

  Widget _buildItem(String item, Animation animation) {
    if(_data.length % 2 == 0) {
      return SlideTransition(position: animation.drive(Tween(end: Offset(0,0.5),begin: Offset(1,0.5))),child: Card(
        child: ListTile(
          title: Text(
            item,
            style: TextStyle(fontSize: 20),
          ),
        ),
      ),);
    }
    return SizeTransition(
      sizeFactor: animation,
      child: Card(
        child: ListTile(
          title: Text(
            item,
            style: TextStyle(fontSize: 20),
          ),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        actions: <Widget>[
          RaisedButton(
            child: Text('增加'),
            onPressed: () {
              _insertSingleItem();
            },
          ),
          RaisedButton(
            child: Text('删除'),
            onPressed: () {
              _removeSingleItems();
            },
          )
        ],
      ),
      body: AnimatedList(
        key: _listKey,
        initialItemCount: _data.length,
        itemBuilder: (BuildContext context, int index, Animation animation) {
          return _buildItem(_data[index], animation);
        },
      ),
    );
  }
}
